import com.fazecast.jSerialComm.SerialPort;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SerialPortReceiver {
    public static void main(String[] args) {
        // 创建SerialPort对象
        SerialPort serialPort = SerialPort.getCommPort("COM9");
        // 配置串口参数
        serialPort.setBaudRate(38400);
        serialPort.setNumDataBits(8);
        serialPort.setNumStopBits(1);
        serialPort.setParity(SerialPort.NO_PARITY);
        serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 100000, 0);



        Pattern pattern = Pattern.compile("\\{(.*?)\\}");

        // 打开串口连接
        if (serialPort.openPort()) {
            System.out.println("串口已打开");
        } else {
            System.out.println("无法打开串口");
            return;
        }

        // 监听串口输入流
        InputStream in = serialPort.getInputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            // 连接数据库
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/serialport?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull";
            String username = "root";
            String password = "root";
            conn = DriverManager.getConnection(url, username, password);

            // 插入数据的SQL语句
            String sql = "INSERT INTO demo1(str) VALUES(?)";
            pstmt = conn.prepareStatement(sql);

            while ((len = in.read(buffer)) > -1) {
                // 处理接收到的数据
                String receivedData = new String(buffer, 0, len);

                Matcher matcher = pattern.matcher(receivedData);
                if (matcher.find()) {
                    String data = matcher.group(1); // 获取匹配到的第一个子串

                    String value = data.substring(data.indexOf('=') + 1);
                    double num = Double.parseDouble(value);

                    System.out.println(data); 
                    // 存入数据库
                    pstmt.setDouble(1, num);
                    pstmt.executeUpdate();
                }

                //System.out.print(receivedData);
                //
                //// 存入数据库
                //pstmt.setString(1, receivedData);
                //pstmt.executeUpdate();
            }
        } catch (Exception e) {
            System.out.println("接收或存储数据时发生异常：" + e.getMessage());
        } finally {
            // 关闭数据库连接
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 关闭串口连接
            serialPort.closePort();
            System.out.println("串口已关闭");
        }
    }
}
